<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
<div id="app">
    <h1>{{title}}</h1>

    <a href="#/login?name=hhl&password=123">用户登录</a>
    <a href="#/reg/hhl">用户注册</a>
    <hr>

    <!-- 切换路由标签 -->
    <router-link to="login?name=hhl&password=123">用户登录</router-link>
    <hr>

    <!-- 切换路由标签 -->
    <router-link :to="{path:'/login',query:{name:'hhl',password:123}}">路径？号传参</router-link>
    <hr>

    <!--名称切换路由：根据路由对象名称切换路由显示不同组件   根据路由名称切换路由只能使用router-link-->
    <router-link :to="{name:'Login',query:{name:'hhl',password:123}}">路由名称？号传参</router-link>
    <hr>

    <router-link :to="{name:'Reg',params:{name:'hhl'}}">路由名称/传参</router-link>
    <hr>


    <button @click="login">登录</button>
    <button @click="reg">注册</button>

    <!-- 显示路由组件标签 -->
    <router-view></router-view>


</div>
</body>
</html>

<script src="../js/v2.6.10/vue.js"></script>
<script src="../js/vue-router.js"></script>
<script>

    const login = {
        template: `<div><h3>用户登录</h3></div>`,
        created(){
            console.log(this)
            console.log(this.$route.query.name)
            console.log(this.$route.query.password)
        }
    }

    const reg = {
        template: `<div><h3>用户注册</h3></div>`,
        created() {
            console.log(this.$route.params.name)
            console.log(this.$route.params.name)
        }
    }

    const notFound = {
        template: `<div><h3>404 页面走丢了</h3></div>`,
    }

    const router = new VueRouter({
        routes: [
            {path: '/login', component: login, name: 'Login'},
            {path: '/reg/:name', component: reg, name: 'Reg'},
            {path: '*', component: notFound},
        ]
    })

    //解决同意路由多次奇幻报错的问题
    const originalPush = VueRouter.prototype.push;
    VueRouter.prototype.push = function push(location){
        return originalPush.call(this ,location).catch(err=>err)
    }


    const app = new Vue({
        el: "#app",
        data: {
            title: '路由传递参数'
        },
        methods: {
            reg(){
                // this.$route  当前路由对象      this.$router    路由管理器对象
                console.log(this)
                console.log('注册')
                // this.$router.push('/reg');//切换路由
                // this.$router.push({path:'/reg'});
                this.$router.push({name:'Reg'});//使用名称切换
            },
            login(){
                if(this.$route.name!='Login') {
                    this.$router.push({name: 'Login'})
                }
            }

        },
        router,
        components: {
            //注册局部组件
            login, reg,notFound
        }
    });

</script>